// packageA/others/materialCenter/materialCenter.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: "0",
    status: false,
    second_catgory: [],
    parentid: '0',
    childid: '',
    search_title: '',
    language: '',
    show1: false,
    posterShow: false,
    list: [],
    posterImg: '',
    // more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    timestart: 0,
    timeend: 0,
    kFootshow: true,
    iPnoneBottomBol: false,
    posterId: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getiPnoneBottom();
    this.initData();
    this.getData();
    this.getCatgory();
  },
  onPageScroll() {
    // this.setData({
    //   status:false
    // });
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let basic_info = wx.getStorageSync('yz_basic_info');
    this.setData({
      theme_color: basic_info.theme_color
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  initData() {
    this.setData({
      show1: false,
      posterShow: false,
      list: [],
      posterImg: '',
      // more
      isLoadMore: true,
      page: 1,
      total_page: 0
    });
  },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.index');
    that.setData({
      isLoadMore: false,
      page: 1
    });
    let json = {
      page: this.data.page,
      parentid: this.data.parentid,
      childid: this.data.childid,
      search_title: this.data.search_title
    };
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isLoadMore: true,
            total_page: res.data.list.last_page
          });

          that.setData({
            list: res.data.list.data
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  changeSecond(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      childid: id
    });
    this.getData();
  },
  close() {
    this.setData({
      status: false
    });
  },
  onClick(e) {
    this.setData({
      parentid: e.detail.name,
      childid: ''
    });
    if (this.data.parentid == '0') {
      this.setData({
        second_catgory: [],
        status: false
      });
    } else {
      this.data.catgoryList.forEach((item, index) => {
        if (item.id == this.data.parentid) {
          this.setData({
            second_catgory: item.childrens,
            status: true
          });
          if (item.childrens.length > 0) {
            this.setData({
              childid: item.childrens[0].id,
            })
          }
        }
      });
    }
    this.getData();
  },
  // 获取更多数据
  getMoreData() {

    let that = this;
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.index');
    that.setData({
      isLoadMore: false // 防止多次请求分页数据
    });

    if (that.data.page >= that.data.total_page) {
      return;
    } else {
      that.setData({
        page: that.data.page + 1,
      });
      app._getNetWork({
        url: urlStr,
        data: {
          page: that.data.page,
          parentid: that.data.parentid,
          childid: that.data.childid,
          search_title: that.data.search_title
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let myData = res.data.list.data;
            that.setData({
              isLoadMore: true,
              list: that.data.list.concat(myData) // 数组拼接
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  showimage(e) {
    let imgarr = e.currentTarget.dataset.images;
    let imgidx = e.currentTarget.dataset.imgidx;
    wx.previewImage({
      current: imgarr[imgidx] ? imgarr[imgidx] : '', // 当前显示图片的http链接
      urls: imgarr ? imgarr : [] // 需要预览的图片http链接列表
    });
  },
  toSousuo() {

    wx.navigateTo({
      url: '/packageA/others/materialSearch/materialSearch'
    });
  },
  toDetail(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/others/materialDetail/materialDetail?id=' + id,
    })
  },
  toGoods(e) {
    let good_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + good_id
    });
  },
  update(e) {
    let id = e.currentTarget.dataset.id;
    let title = e.currentTarget.dataset.title;
    wx.setClipboardData({
      data: title ? title : '',
      success(res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none',
          duration: 1500
        });
      },
      fail() {
        wx.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 1500
        });
      }
    });
    this.setData({
      show1: true
    });

    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.updateNum');
    app._getNetWork({
      url: urlStr,
      data: {
        id: id,
        params: 'share'
      },
      success: function (resdata) {},
      fail: function (res) {
        console.log(res);
      }
    });
  },
  show1Close() {
    this.setData({
      show1: false
    });
  },
  getCatgory() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.getCategoryList');
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            catgoryList: res.data
          });
          console.log(that.data.catgoryList);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  download(e) {
    let images = e.currentTarget.dataset.images || [];
    let video = e.currentTarget.dataset.video || [];
    if (images.length > 0) {
      wx.showLoading({
        title: '正在下载图片...',
      })
      this.loadImg(images);
    }
    if (video && video.video_url) {
      wx.showLoading({
        title: '正在下载视频...',
      })
      this.loadVideo(video);
    }
  },
  loadImg(images) {
    images.forEach((item) => {
      wx.downloadFile({
        url: item, //需要下载的图片url
        success: function (res) { //成功后的回调函数
          wx.saveImageToPhotosAlbum({ //保存到本地
            filePath: res.tempFilePath,
            success(res) {
              wx.hideLoading();
              wx.showToast({
                title: '图片下载成功',
                icon: 'success',
                duration: 2000
              });
            },
            fail: function (err) {
              wx.hideLoading();
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata);
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      console.log('获取权限成功，给出再次点击图片保存到相册的提示。');
                    } else {
                      console.log('获取权限失败，给出不给权限就无法正常使用的提示');
                    }
                  }
                });
              }
            }
          });
        }
      });
    });
  },
  loadVideo(video) {
    wx.downloadFile({
      url: video.video_url, //需要下载的视频url
      success: function (res) { //成功后的回调函数
        wx.saveVideoToPhotosAlbum({ //保存到本地
          filePath: res.tempFilePath,
          success(res) {
            wx.hideLoading();
            wx.showToast({
              title: '视频下载成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: function (err) {
            wx.hideLoading();
            if (err.errMsg === "saveVideoToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata);
                  if (settingdata.authSetting['scope.saveVideoToPhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击视频保存到相册的提示。');
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示');
                  }
                }
              });
            }
          }
        });
      }
    });
  },
  // 海报生成
  postShow(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    if (!id) {
      wx.showToast({
        title: '该素材未设置关联商品',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    if (that.data.posterImg && this.data.posterId == id) {
      this.setData({
        posterShow: true
      });
    } else {
      this.data.posterId = id;
      wx.showLoading({
        title: '海报生成中',
      });
      let urlStr = app.getNetAddresss('goods.goods-poster.generate-goods-poster');
      app._getNetWork({
        url: urlStr,
        data: {
          id: id
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              posterShow: true,
              posterImg: res.data.image_url
            });
          } else {
            that.setData({
              posterShow: false
            });
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          }
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  posterShowClose() {
    this.setData({
      posterShow: false
    });
  },
  // 点击开始时的时间
  timestart: function (e) {
    var _this = this;
    _this.setData({
      timestart: e.timeStamp
    });
  },

  // 点击结束的时间
  timeend: function (e) {
    var _this = this;
    _this.setData({
      timeend: e.timeStamp
    });
  },
  saveImg() {
    // var times = _this.data.timeend - _this.data.timestart
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = this.data.posterImg;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        console.log(res);
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              console.log('当初用户拒绝，再次发起授权');
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });

  },
});